package com.smedi.ismedi.inmail.core.domain.service.impl;

import com.smedi.ismedi.inmail.core.domain.aggregatemodel.MessageInfo;
import com.smedi.ismedi.inmail.core.domain.aggregatemodel.MessageRecord;
import com.smedi.ismedi.inmail.core.domain.repository.MessageInfoRepository;
import com.smedi.ismedi.inmail.core.domain.repository.MessageRecordRepository;
import com.smedi.ismedi.inmail.core.domain.service.MessageDomainService;
import com.smedi.ismedi.web.starter.util.DozerUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author u
 */
@Service
@AllArgsConstructor
public class MessageDomainServiceImpl implements MessageDomainService {
    private final DozerUtil dozerUtil;

    private final MessageInfoRepository messageInfoRepository;

    private final MessageRecordRepository messageRecordRepository;

    @Override
    public List<MessageRecord> sendMessage(List<MessageInfo> messageInfos, List<Long> userIds) {
        List<MessageRecord> messageRecords = new ArrayList<>();
        LocalDateTime localDateTime = LocalDateTime.now();
        List<MessageInfo> list = messageInfoRepository.doInsertList(messageInfos);
        for (MessageInfo messageInfo : list) {
            for (Long id : userIds) {
                MessageRecord messageRecord = dozerUtil.convertor(messageInfo, MessageRecord.class);

                messageRecord.setUserId(id);
                messageRecord.setMessageId(messageInfo.getId());
                messageRecord.setMessageRead(Boolean.FALSE);
                messageRecord.setPushTime(localDateTime);

                messageRecords.add(messageRecord);
            }
        }
        return messageRecordRepository.doInsertList(messageRecords);
    }

    @Override
    public List<MessageRecord> readMessages(List<Long> messageIds) {
        List<MessageRecord> messageRecords = messageRecordRepository.doList(messageIds);
        for (MessageRecord messageRecord : messageRecords) {
            messageRecord.setMessageRead(Boolean.TRUE);
        }
        return messageRecordRepository.doUpdateList(messageRecords);
    }

    @Override
    public MessageRecord queryMessages(Long messageId) {
        MessageRecord messageRecord = messageRecordRepository.doQuery(messageId);

        messageRecord.setMessageRead(Boolean.TRUE);

        return messageRecordRepository.doUpdate(messageRecord);
    }

    @Override
    public Boolean deleteMessages(List<Long> messageIds) {
        return messageRecordRepository.doDelete(messageIds);
    }
}
